/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

var $ = require('jquery');
var ClipboardJS = require('clipboard');
var app = {};

app.tooltips = function (text, sec) {
    var html = '<div class="tooltips"><span>' + text + '</span></div>';
    var obj = $(html);
    $('body').append(obj);
    setTimeout(function () {
        obj.fadeOut('slow', function () {
            this.remove();
        })
    }, sec);
}

app.dialog = function (title, body, submit) {
    var html = '<div class="dialog">\
		<div class="warp">\
			<div class="title"><span>' + title + '</span><i class="close">x</i></div>\
			<div class="body">\
				' + body + '\
			</div>\
			<div class="btn">\
				<span class="submit">确定</span>\
				<span class="close">取消</span>\
			</div>\
		</div>\
	</div>';
    var dialog = $(html);
    $('body').append(dialog);
    dialog.find('.close').click(function () {
        dialog.remove();
    });
    dialog.find('.submit').click(function () {
        submit && submit();
        dialog.remove();
    })
}

app.productHover = function () {
    $('.showmore').mouseover(function () {
        $(this).addClass('hover');
    });

    $('.showmore').mouseout(function () {
        $(this).removeClass('hover');
    })
}

app.copyBtn = function () {
    var copyRes = new ClipboardJS('.copyBtn', {
        text: function (btn) {
            var ele = $(btn).data('ele');
            var item = $(ele).html();
            var copyinfo = item.replace(/	/g, '').replace(/<br>/g, "\r\n").replace('&amp;', '&');
            console.log('复制后的信息');
            console.log(copyinfo);
            return copyinfo;
        }
    });
    copyRes.on('success', function (e) {
        app.tooltips('复制成功', 1000);
        e.clearSelection();
    })

    copyRes.on('error', function (e) {
        app.tooltips('复制失败', 1000);
    })
}

app.listCopy = function () {
    $('.doCopy').mouseover(function (e) {
        var item = $(this).parent().parent().parent().parent();
        var copys = item.find('.copys');
        var width = $(window).width();
        var x = item.offset().left;
        if (x + 600 > width) {
            copys.css('left', '-300px');
        }
        copys.fadeIn();
    })
    $('.doCopy').mouseout(function () {
        $(this).parent().parent().parent().parent().find('.copys').fadeOut();
    })
    var copyRes = new ClipboardJS('.doCopy', {
        target: function (btn) {
            console.log(btn.parentNode.parentNode.parentNode.parentNode.querySelector('div'))
            return btn.parentNode.parentNode.parentNode.parentNode.querySelector('div');
        }
    });
    // return false ;
    /*  var copyRes = new ClipboardJS('.doCopy', {
          target: function (btn) {
              console.log('===')
              var item = $(btn).parent().parent().parent().parent();
              console.log(item.find('.copys').html())
             // var item = item.find('.copys').html();
             // console.log(item.find('.copys'))
                  return  item.find('.copys').html() ;
              var  copyinfo=item.replace(/	/g, '').replace(/<br>/g, "\r\n").replace('&amp;', '&');
              // console.log('复制后的信息');
              // console.log(copyinfo);
              return copyinfo;
          }
      });*/
    copyRes.on('success', function (e) {
        console.log('success', e)

        app.tooltips('复制成功', 1000);
        e.clearSelection();
    })

    copyRes.on('error', function (e) {
        console.log('error', e)
        app.tooltips('复制失败', 1000);
    })
}

app.secKillCopy = function () {
    var copyRes = new ClipboardJS('.seckillCopy', {
        target: function (btn) {
            console.log(btn.parentNode.parentNode.parentNode.parentNode.querySelector('.copyText'))
            return btn.parentNode.parentNode.parentNode.parentNode.querySelector('.copyText');
        }
    });
    copyRes.on('success', function (e) {
        console.log('success', e)
        app.tooltips('复制成功', 1000);
        //e.clearSelection();
    })
    copyRes.on('error', function (e) {
        app.tooltips('复制失败', 1000);
    })
}

app.oneSecKillCopy = function () {
    // console.log('oneSecKillCopy')
    /* var copyRes = new ClipboardJS('.oneSecKillCopy', {
         text: function (btn) {
             var item = $(btn).parent().parent();
             var item = item.find('.copyText').html();
             var  copyinfo=item.replace(/	/g, '').replace(/<br>/g, "\r\n").replace('&amp;', '&');
             console.log('复制后的信息');
             console.log(copyinfo);
             return copyinfo;
         }
     });*/
    var copyRes = new ClipboardJS('.oneSecKillCopy', {
        target: function (btn) {
            console.log(btn.parentNode.querySelector('.copyText'))
            return btn.parentNode.querySelector('.copyText');

        }
    });
    copyRes.on('success', function (e) {
        app.tooltips('复制成功', 1000);
    })
    copyRes.on('error', function (e) {
        app.tooltips('复制失败', 1000);
    })
}

app.process = function () {
    var pross = $('.process-count');
    if (pross.length < 1) return;
    pross.each(function () {
        var total = parseInt($(this).find('.total').text());
        var num = parseInt($(this).find('.num').text());
        var dad = $(this).parent().parent().find('.process');
        var width = parseInt((total - num) / total * 100);
        $(dad).find('span').css('width', width + '%');
    })
}

app.showBigPhoto = function () {
    var photos = $('.productPhotos .thumb img').mouseover(function () {
        $(this).parent().find('.active').removeClass('active');
        $(this).addClass('active');
        var src = $(this).data('big');
        if (src) {
            var img = $(this).parent().parent().find('.bigPhoto').attr('src', src);
        }
    });

}

app.getNow = function () {
    var t = (new Date()).getTime();
    return t / 1000;
}

app.timer = function () {
    var timers = $('.timers');
    if (timers.length < 1) return;
    var ts = setInterval(function () {
        timers.each(function () {
            var now = parseInt((new Date()).getTime() / 1000);
            var date = parseInt(Date.parse($(this).data('date')) / 1000);
            var t = date - now;
            if (t < 1) {
                $(this).html('');
            } else {
                var d = parseInt(t / 86400);
                if (d < 1) {
                    d = 0;
                } else {
                    t = t % 86400;
                }
                var h = parseInt(t / 3600);
                if (h < 1) {
                    h = 0;
                } else {
                    t = t % 3600;
                }
                var m = parseInt(t / 60);
                if (m < 1) {
                    m = 0;
                } else {
                    t = t % 60;
                }
                var s = t;
                $(this).find('.d').html(d);
                $(this).find('.h').html(h);
                $(this).find('.m').html(m);
                $(this).find('.s').html(s);
            }
        });
    }, 1000);
}

app.addBacktop = function () {
    var a = $('body').find('.backtop');
    if (a.length < 1) {
        var backtop = '<div class="backtop"><a href="#">返回顶部</a></div>'
        $('body').append(backtop);
    }
}
app.removeBacktop = function () {
    $('body').find('.backtop').remove();
}

$(window).scroll(function (e) {
    if ($(window).scrollTop() < 280) {
        $('.header').removeClass('header-small');
        app.removeBacktop();
    } else {
        $('.header').addClass('header-small');
        app.addBacktop();
    }
});

//商品纠错点击事件
$('.error').click(function () {
    let token = localStorage.getItem("token");
    let token_expires = localStorage.getItem("token_expires");
    if (token && token_expires) {
        let token_date = new Date(token_expires.replace(/-/g, '/'));
        let now_time_ = get_now_time();
        let now_time = new Date(now_time_.replace(/-/g, '/'));
        if (now_time > token_date) {
            app.tooltips('请先登录！', 2000);
            return false;
        }
    } else {
        app.tooltips('请先登录！', 2000);
        return false;
    }
    var cover = '';
    var title = '';
    var link = '';
    var item = $(this).parent().parent().parent().parent();
    if (item.attr('class') == 'item') {
        cover = item.find('.cover').find('img:first').attr('src');
        title = item.find('.title:first').text();
        link = item.find('.cover').find('a:first').attr('href');
        gid = item.find('.find_good_id').text();
        goodstype = item.find('.find_good_type').text();
    } else {
        item = item.parent().parent();
        cover = item.find('.cover').find('img:first').attr('src');
        title = item.find('.title h1').text();
        link = item.find('.cover').find('a:first').attr('href');
        gid = item.find('.find_good_id').text();
        goodstype = item.find('.find_good_type').text();
    }
    var html = '<form class="errorform">\
		<input type="hidden" name="link" value="' + link + '">\
		<input type="hidden" name="gid" value="' + gid + '">\
		<input type="hidden" name="goodstype" value="' + goodstype + '">\
		<div><label>商品封面</label><img src="' + cover + '" alt="cover"></div>\
		<div><label>商品标题</label><input type="input" readonly value="' + title + '"></div>\
		<div><label>纠错类型</label><select name="type">\
		<option value="0">价格问题</option>\
		<option value="1">优惠券问题</option>\
		<option value="2">佣金问题</option>\
		<option value="3">商品/售后问题</option>\
		<option value="4">其他问题</option></div>\
		<option value="5">商品已下架平台未下架</option></select></div>\
		<div><label>问题描述</label><textarea name="content" placeholder="填写商品存在的错误问题"></textarea></div>\
	</form>';
    app.dialog('商品纠错', html, function () {
        var arr = $('.errorform').serializeArray();
        var json = {};
        arr.forEach(function (item) {
            var name = item.name;
            var value = item.value;
            if (!json[name]) {
                json[name] = value;
            } else if ($.isArray(json[name])) {
                json[name].push(value);
            } else {
                json[name] = [json[name], value];
            }
        });
        $.ajax({
            type: 'post',
            timeout: 5000, // 超时时间 10 秒
            headers: {
                'Authorization': "Bearer " + localStorage.getItem("token"),
                'Accept': "application/json"
            },
            url: '/api/addcorrection',
            data: {"gid": json.gid, "type": json.type, "content": json.content, "goodstype": json.goodstype},
            success: function (data) {
                console.log('----------');
                if (typeof data === 'string') {
                    var obj = JSON.parse(data)
                }
                if (obj.code == 0) {
                    app.tooltips('提交成功', 1000);
                } else {
                    app.tooltips(obj.msg, 1000);
                }
            },
            error: function (err) {
            },
            complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数　
            }
        })
    });
});

app.UserIsLogin = function () {
    let token = localStorage.getItem("token");
    let token_expires = localStorage.getItem("token_expires");
    if (token && token_expires) {
        let token_date = new Date(token_expires.replace(/-/g, '/'));
        let now_time_ = get_now_time();
        let now_time = new Date(now_time_.replace(/-/g, '/'));
        /*        console.log('-----------')
                console.log(now_time)
                console.log(token_date)*/
        if (now_time < token_date) {
            $('._top_info').html(' <a target="_blank" href="/ucenter#home">放单平台</a>\n' +
                '        <a target="_blank" href="/ranking">招商排行榜</a>\n' +
                '        <a target="_blank" href="/ucenter#home">用户中心</a>'
            )
        } else {
            $('._top_info').html('<a target="_blank" href="/ranking">招商排行榜</a>\n' +
                '        <a target="_blank" href="/ucenter">登录</a>\n' +
                '        <a target="_blank" href="/register" class="reg">注册</a>')
        }
    } else {
        $('._top_info').html(' <a target="_blank" href="/ranking">招商排行榜</a>\n' +
            '        <a target="_blank" href="/ucenter">登录</a>\n' +
            '        <a  target="_blank" href="/register" class="reg">注册</a>')
    }
}
app.userinfoshow = function () {
    $('#userContact').mousemove(function () {
        $('#contactBox').fadeIn();
    })
    $('#userContact').mouseout(function () {
        $('#contactBox').fadeOut();
    })
}

function get_now_time() {
    let date = new Date();
    let year = date.getFullYear(); //获取当前年份
    let mon = date.getMonth() + 1; //获取当前月份
    let day = date.getDate(); //获取当前日

    let h = date.getHours(); //获取小时
    let m = date.getMinutes(); //获取分钟
    let s = date.getSeconds(); //获取秒
    return year + '-' + mon + '-' + day + ' ' + h + ':' + m + ':' + s;
}
//init
app.init = function () {
    this.productHover();
    this.copyBtn();
    this.timer();
    this.process();
    this.showBigPhoto();
    this.secKillCopy();
    this.oneSecKillCopy();
    this.listCopy();
    this.UserIsLogin();
    this.userinfoshow();
}
app.init();

//global exports
window.$ = $;
window.app = app;
